package com.tanhua.server.interceptor;

import com.alibaba.fastjson.JSON;
import com.tanhua.common.utils.Cache;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.server.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author 王加鑫
 * @Date 2021/09/05 16:01
 * @Since JDK 1.8
 */
@Component
public class RedisCacheInterceptor implements HandlerInterceptor {

    @Value("${tanhua.cache.enable}")
    private Boolean enable;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断条件
        //是否开启缓存
        if(!enable){
            return true;
        }

        //是否是方法处理器
        if(!(handler instanceof  HandlerMethod)){
            return true;
        }

        //判断是否为get请求
        if(!((HandlerMethod) handler).hasMethodAnnotation(GetMapping.class)){
            return true;
        }

        //判断是否加了Cache注解
        if(!((HandlerMethod) handler).hasMethodAnnotation(Cache.class)){
            return true;
        }

        //缓存命中
        String redisKey = createRedisKey(request);
        String cacheData = redisTemplate.opsForValue().get(redisKey);
        if(StringUtils.isEmpty(cacheData)){
            return true;
        }

        // 将data数据进行响应
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(cacheData);
        return false;
    }


    /**
     * 只有return true的时候才能走到这里
     * @param request
     * @return
     */
    public static String createRedisKey(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        String parm = JSON.toJSONString(request.getParameterMap());
        String token = request.getHeader("Authorization");
        //生成redisKey
        String redisKey = "SERVER_CACHE_DATA_" + DigestUtils.md5Hex(url + "_" + parm + "_" + token);
        return redisKey;
    }
}
